package com.juc.learn.countdownlacth;

import java.util.concurrent.CountDownLatch;

/**
 * ClassName:CountDownLatchDemo
 * Package:com.juc.learn.countdownlacth
 * Description:减少计数
 *
 * @Author:@郭先森
 * @Create:2025/7/27 - 21:03
 * @Version:v1.0
 */
//演示CountDownLatch，假设教室现在有6个同学，当它们都离开教室后，才能关闭教室门
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        //6个同学离开教室
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"号同学离开了教室");
            },String.valueOf(i)).start();
        }
        System.out.println(Thread.currentThread().getName()+"班长锁门了");
        /*
        * 4号同学离开了教室
        * 1号同学离开了教室
        * 0号同学离开了教室
        * main班长锁门了
        * 2号同学离开了教室
        * 5号同学离开了教室
        * 3号同学离开了教室
        * */
        Thread.sleep(5000);
        System.out.println("***************************************");
        //使用CountDownLatch,设置减少计数的初始值
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"号同学离开了教室");
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        countDownLatch.await();//会阻塞直到countDown减为0后
        System.out.println(Thread.currentThread().getName()+"班长锁门了");
    }

}
